package com.hefu.virtuallife.ui;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;

import com.hefu.virtuallife.R;
import com.hefu.virtuallife.base.BaseActivity;

import java.util.Random;

import butterknife.BindView;
import butterknife.OnTouch;


/**
 * Created by zc on 2018/5/29.
 */

public abstract class VoiceActivity extends BaseActivity {
    protected static final int DRAW_VOLUME = 1001;

    private volatile int lastIndex;

    @BindView(R.id.iv_volume)
    ImageView iv_volume;
    @BindView(R.id.voice_btn)
    ImageView voice_btn;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);
    }

    public Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            drawVolume();
            sendEmptyMessageDelayed(DRAW_VOLUME, 500);
        }

    };

    @OnTouch(R.id.voice_btn)
    protected boolean onVoiceTouch(View v, MotionEvent event){

        if (event.getAction() == MotionEvent.ACTION_UP){
            iv_volume.setVisibility(View.GONE);
            mHandler.removeMessages(DRAW_VOLUME);
            uiProcess();
        } else if(event.getAction() == MotionEvent.ACTION_DOWN){
            iv_volume.setVisibility(View.VISIBLE);
            mHandler.sendEmptyMessage(DRAW_VOLUME);
        }
        return true;
    }

    private void drawVolume() {

        int i = new Random().nextInt(4) + 1;
        if (i == lastIndex){
            i = (i - 1 == 0) ? i + 1 : i - 1;
        }
        lastIndex = i;
        int resId = getResources().getIdentifier("volume_" + i, "drawable", getPackageName());

        iv_volume.setImageResource(resId);
    }

    protected abstract void uiProcess();

}
